package com.wty.good.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wty.commons.id.IdWorker;
import com.wty.good.mapper.CategoryMapperWty;
import com.wty.good.pojo.CategoryWty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @Author:wangtianyu
 * @Date：Created on 2020/4/23 0023 13:04
 */
@Service
public class CategoryServiceWty {

    @Autowired
    private CategoryMapperWty categoryMapper;

    @Autowired
    private IdWorker idWorker;

    /**
     * 如果在高并发的场景下，
     * 比如说游戏开服的当天会出现大量用户注册的场景，
     * 很有可能用户名会重复,可用通过redis,
     * 用户注册时候先到redis中查询 游戏昵称 是否可用注册，如果可用注册则将 游戏昵称 保存在redis（分布式共享锁）后去关系型数据库注册
     * 如果不可能可用注册则提示用户
     *
     * 分布式共享锁 redis zookeeper
     * @param category
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor = RuntimeException.class) // 如果发生运行时异常就回滚
    public synchronized CategoryWty addCategory(CategoryWty category) throws Exception {

        // 判断商品名称不能重复
        QueryWrapper<CategoryWty> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("catename",category.getCatename());
        int checkCount = categoryMapper.selectCount(queryWrapper);
        if (checkCount > 0) {
            throw new RuntimeException();
        }
        // 补全参数
        category.setCateid(idWorker.nextId());
        category.setCreatetime(new Date());
        // 添加
        int count = categoryMapper.insert(category);
        // 返回判断
        if (count == 0) {
            throw new RuntimeException();
        }
        return category;
    }

    public List<CategoryWty> selectList()throws Exception {
        return categoryMapper.selectList(null);
    }
}
